#coding=utf-8
import glob
import os
import operator
import random
import shutil
from tqdm import tqdm
import copy

def countTotalImgs_old(imgPath,num):
    for filename in os.listdir(imgPath):
        pathname=os.path.join(imgPath,filename)
        subfix=os.path.splitext(pathname)[-1]
        if(os.path.isfile(pathname) and operator.eq(subfix,'.bitlog')):
            num[0] += 1
        elif(os.path.isdir(pathname)):
            countTotalImgs_old(pathname,num)

def get_target_files(rootpath,rules=['.bmp'],keyword=''):
    files_list = []
    for root, dirs, files in os.walk(rootpath):
        if dirs:
            for sDir in dirs:
                for i in range(len(rules)):
                    imgs_list = glob.glob(os.path.join(root, sDir) + '/*'+rules[i])
                    files_list.extend(imgs_list)
        else:
            for i in range(len(rules)):
                imgs_list = glob.glob(rootpath+'/*'+rules[i])
                files_list.extend(imgs_list)

    if len(keyword)>=2:
        files_list1=[]
        # if cmp(keyword[0],'FILENAME')==0:
        if operator.eq(keyword[0], 'FILENAME'):
            for i in range(len(files_list)):
                filename=get_file_name(files_list[i])
                # if keyword[1] in filename:
                flag=any([filename.find(keyname)>=0 for keyname in keyword[1:]])
                # print(filename,flag)
                if (flag):
                    files_list1.append(files_list[i])
        elif operator.eq(keyword[0],'FILEPATH'):
            for i in range(len(files_list)):
                # if keyword[1] in files_list[i]:
                filedirect = get_file_direct(files_list[i])
                flag=any([filedirect.find(keyname)>=0 for keyname in keyword[1:]])
                if (flag):
                    files_list1.append(files_list[i])
        else:
            print('keyword error!')
        files_list=files_list1
    return files_list

def get_target_directs_files(rootpath,directs,rules=['.ppm'],keyword=''):
    files_list = []
    for direct in directs:
        rootpath_d=os.path.join(rootpath,direct)
        for root, dirs, files in os.walk(rootpath_d):
            if dirs:
                for sDir in dirs:
                    for i in range(len(rules)):
                        imgs_list = glob.glob(os.path.join(root, sDir) + '/*'+rules[i])
                        files_list.extend(imgs_list)
            else:
                for i in range(len(rules)):
                    imgs_list = glob.glob(rootpath_d+'/*'+rules[i])
                    files_list.extend(imgs_list)

    if len(keyword)>1:
        files_list1=[]
        if operator.eq(keyword[0],'FILENAME'):
            for i in range(len(files_list)):
                filename=get_file_name(files_list[i])
                if keyword[1] in filename:
                    files_list1.append(files_list[i])
        elif operator.eq(keyword[0],'FILEPATH'):
            for i in range(len(files_list)):
                if keyword[1] in files_list[i]:
                    files_list1.append(files_list[i])
        else:
            print('keyword error!')
        files_list=files_list1
    return files_list

def getShuffleList(rootpath):
    files_list=[]
    for root,dirs,files in os.walk(rootpath):
        for sDir in dirs:
            imgs_list = glob.glob(os.path.join(root, sDir) + '/*.bmp')
            files_list.extend(imgs_list)

    random.shuffle(files_list)
    return files_list

def filter_big_direct(rootpath):
    num=0
    for file in os.listdir(rootpath):
        filepath=os.path.join(rootpath,file)
        if(os.path.isfile(filepath) and get_file_subfix(filepath)=='.JPG'):
            # filelist=glob.glob(filepath)
            # if(len(filelist)>1):
            #     print
            num+=1
    print(num)

def copy_JPG():
    src_rootpath='/root/100_data/aw_zhuatu/20190802_iphone_person_image'
    dst_rootpath='/root/100_data/aw_zhuatu/20190801_iphone_person_image'
    num = 0
    for file in os.listdir(src_rootpath):
        filepath = os.path.join(src_rootpath, file)
        if (os.path.isfile(filepath) and get_file_subfix(filepath) == '.JPG'):
            num += 1
            print(num)
            # file1='0802_'+file
            dst_filepath=filepath.replace(src_rootpath,dst_rootpath)
            # dst_filepath=os.path.join(dst_rootpath,file1)
            shutil.copyfile(filepath,dst_filepath)
    print(num)

#先把字符串变成list，在list中insert，然后连接List变为字符串
def insert_str(str1, index,str2):
    return str1[:index] + str2 + str1[index:]

#遍历文件夹，修改文件名
def rename_files():
    src_root='Z:/data/dms_20200603/0724_test/phone'
    filelist=get_target_files(src_root,['.jpg'])
    length=len(filelist)
    print(length)

    for i in tqdm(range(length)):
        filepath=filelist[i]
        file_direct=get_file_direct(filepath)
        file_fullname=get_file_fullname(filepath)
        # index=file_fullname.find('differ')
        # file_fullname1=insert_str(file_fullname,index+6,'_')
        # file_fullname1=file_fullname.replace('ir1.jpgnv21_','')
        file_fullname1=file_fullname.replace('.jpg','-1-0.jpg')

        dst_filepath=os.path.join(file_direct,file_fullname1)
        print(dst_filepath)
        # os.rename(filepath,dst_filepath)
        # break

def get_file_direct(filepath):
    rslash=filepath.rfind('\\')
    lslash=filepath.rfind('/')
    index=max(rslash,lslash)
    if index:
        return filepath[0:index]
    else:
        return None

def get_file_name(filepath):
    rdot=filepath.rfind('.')
    rslash = filepath.rfind('\\')
    lslash = filepath.rfind('/')
    index = max(rslash, lslash)
    if index:
        return filepath[index+1:rdot]
    else:
        return None

#返回的扩展名为'.jpg','.bmp'
def get_file_subfix(filepath):
    return os.path.splitext(filepath)[-1]

#返回文件的全名file_name+file+subfix，dog.jpg
def get_file_fullname(filepath):
    rslash = filepath.rfind('\\')
    lslash = filepath.rfind('/')
    index = max(rslash, lslash)
    if index:
        return filepath[index+1:]
    else:
        return None


def make_direct_exist(dst_direct):
    if not os.path.exists(dst_direct):
        os.makedirs(dst_direct)

num_total = 0
if __name__ == "__main__":
    # path = 'X:/3_SQA/4_Test_picture/6_人脸抓拍用于活体模型训练/20_活体人脸抓图/aihua_zhuatu/20190428/'
    #
    # num = [0]
    # countTotalImgs_old(path, num)
    # print(num[0])

    # rootpath='/mnt/120_data/aiwinn/live/nir_aihua/train_image2'
    # rootpath='/mnt/100_data/6_Test_public/shengpeng/nir_data/nir_mask/train_mask'
    # directs=['20190530','20190601','20190611','20190613','20190614','20190615','20190617','20190618','20190619','20190620',
    #          '20190621','20190722','20190730','20190731','20190801','20190802']
    # files_list=get_target_directs_files(rootpath,directs,['.ppm'])
    # length=len(files_list)
    # print(length)
    img_path = "/home/simple.sheng/data/2_nir/nir_yzj/20210507_yzj/clip/REAL_test"
    imglist=get_target_files(img_path,['.bmp'])
    length=len(imglist)
    print(length)

    # real_num=0
    # fake_num=0
    # for i in range(length):
    #     if 'REAL' in files_list[i]:
    #         real_num+=1
    #     if 'FAKE' in files_list[i]:
    #         fake_num+=1
    # print(real_num,fake_num)

    # rename_files()
